package main
import (
"fmt"
"net"
"time"
)
func main() {
// Set the timeout to 5 seconds
timeout := 5 * time.Second
// Create a Dialer with the timeout set
dialer := net.Dialer{
Timeout: timeout,
}
// DialTCP with the Dialer
conn, err := dialer.DialTCP("tcp", nil, &net.TCPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: 8080,
})
if err != nil {
fmt.Println("Error:", err)
return
}
// Do something with the connection
fmt.Println("Connection established:", conn)
} 在上面的示例代码中,我们创建了一个 Dialer,并将其 Timeout 字段设置为 5 秒。然后,我们使用该 Dialer 对 tcp 协议的 127.0.0.1:8080 进行拨号,如果成功,就会在标准输出中打印连接已经建立的消息。如果没有建立连接,则会在标准输出中打印错误消息。
|